#!/usr/bin/python
# -*- encoding=UTF-8 -*-


# modify: 2014.08.25
#         remove CMOB from the delete class array, 
#         it's error when delete it in ADA 


import time
import os.path
import codecs
import re

from xml.dom import Node
import xml.dom.minidom as Dom 
 
def remove_whitespace_nodes(node):
    remove_list = []
    for child in node.childNodes:
        if child.nodeType == Node.TEXT_NODE and not child.data.strip():
            remove_list.append(child)
        elif child.hasChildNodes():
            remove_whitespace_nodes(child)

    for node in remove_list:
        node.parentNode.removeChild(node)
        node.unlink()

def save_tidy_xml(doc, xml):
    remove_whitespace_nodes(doc) # safely remove blank line
    xmls = re.sub(r'(<[^/<>]*>)\s*([^<>]*?)\s*(</[^<>]*>)', 
                  r'\1\2\3', doc.toprettyxml())
    xmls = xmls.replace('\t', ' '*2)
    with codecs.open(xml, 'w', 'utf-8') as f:
        f.write(xmls)
    return True

def tidy_xml(path):
    if not os.path.exists(path):
        #print 'File does not exists!'
        return False
    else:
        return save_tidy_xml(Dom.parse(path), path)

def set_value(doc, node, name, value):
    p = doc.createElement('p')
    p.setAttribute('name', name)
    text = doc.createTextNode(value)
    p.appendChild(text)
    node.appendChild(p)

def make_del_xml(xml):
    if not xml or (xml and not os.path.isfile(xml)):
        #print "file not exists."
        return None
    doc = Dom.parse(xml)
    log_node = doc.getElementsByTagName('log')[0]
    log_node.setAttribute('dateTime', 
                          time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
    log_node.setAttribute('user', "limbo")
    log_node.firstChild.data = "delete plan"

    delete_class = ['WCEL', 'WBTS', 'VCEL', 'VBTS', 'WRAB', 'PFL', 'HOPS', 
                    'HOPI', 'HOPL', 'HOPG', 'FMCS', 'FMCI', 'FMCL', 'FMCG', 
                    #'CMOB', 
                    'COCO', 'IPNB', 'IUR', 'WSG', 'IUCSIP', 'IUPSIP']

    modify_class = ['IADA', 'RNC', 'RNMOBI']
    modify_class.extend(delete_class)
    
    class_dict = {}
    
    for node in doc.getElementsByTagName('managedObject'):
        class_name = node.getAttribute('class')
        if class_name not in modify_class:
            node.parentNode.removeChild(node)
            node.unlink()
        else:
            for child in node.childNodes:
                if child.nodeType == Node.ELEMENT_NODE:
                    node.removeChild(child)
                    child.unlink()

            if class_name in delete_class:
                node.setAttribute('operation', "delete")
                if class_name not in class_dict.keys():
                    class_dict[class_name] = []
                class_dict[class_name].append(node)
                node.parentNode.removeChild(node)

            elif class_name in ('IADA', 'RNC'):
                set_value(doc, node, "AutomObjLock", "1")
                set_value(doc, node, "OMSIpAddress", "1.1.1.1")
            elif class_name == "RNMOBI":
                set_value(doc, node, "AnchorFmcsIdentifier", "0")
                set_value(doc, node, "AnchorFmciIdentifier", "0")
                set_value(doc, node, "AnchorHopsIdentifier", "0")
                set_value(doc, node, "AnchorHopiIdentifier", "0")
                set_value(doc, node, "DefaultAuthorisedNetworkId", "0")

    cmData = doc.getElementsByTagName('cmData')[0]
    for var in delete_class:
        if var in class_dict.keys():
            for node in class_dict[var]:
                cmData.appendChild(node)

    xml_name = os.path.basename(xml)
    new_name = xml.replace(xml_name[:-4], "delete")
    save_tidy_xml(doc, new_name)
    return new_name


def tidy_plan(xml):
    if not xml or not os.path.isfile(xml):
        return False
    doc = Dom.parse(xml)
    class_dict = {}
    sort_class = ["RNC", "IADA", "RNAC", "RNCSRV", "RNPS", "RNHSPA", "RNRLC", 
                  "RNTRM", "RNMOBI", "RNFC", "BKPRNC", "PREBTS", "PRNC", 
                  "CBCI", "IUCS", "IUPS", "IUCSIP", "IUPSIP", "COCO", "COSITE",
                  "COSRNC", "DATSYN", "WANE", "IUR", "IPNB", "IPQM", "HOPS", 
                  "HOPI", "HOPG", "HOPL", "IUO", "CMOB", "FMCS", "FMCI", 
                  "FMCG", "FMCL", "WRAB", "WAC", "WSG", "PFL", "TQM", "VBTS", 
                  "VCEL", "WBTS", "WCEL", "WLCSE", "WSMLC", "ADJS", "ADJI", 
                  "ADJD", "ADJE", "ADJG", "ADJL"]
    
    for node in doc.getElementsByTagName('managedObject'):
        class_name = node.getAttribute('class')
        dist_name = \
            (node.getAttribute('distName')).replace('/', '_').replace('-', '')
        if class_name in sort_class:
            if class_name not in class_dict:
                class_dict[class_name] = {}
            class_dict[class_name][dist_name] = node
            node.parentNode.removeChild(node)

    cmData = doc.getElementsByTagName('cmData')[0]
    for name in sort_class:
        if name not in class_dict:
            continue
        for dist_name in sorted(class_dict[name].keys()):
            cmData.appendChild(class_dict[name][dist_name])

    return save_tidy_xml(doc, xml)
